package cn.etgps.etgps.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

import cn.etgps.etgps.R;
import cn.etgps.etgps.base.BaseActivity;
import cn.etgps.etgps.blmanager.LoadingManager;

public class LoadingActivity extends BaseActivity {

    public static final int HANDLER_MSG_GO_MAIN_PATE = 1001;
    /**
     * The manager of the loading page
     */
    public LoadingManager mManager = null;
    /**
     * Handler use to send message to other class
     */
    private Handler mHandler = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loading);
        mHandler = new LoadingActivityHandler(this);
        mManager = new LoadingManager(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        new InitApplicationTask().execute();
        mHandler.sendMessageDelayed(mHandler.obtainMessage(HANDLER_MSG_GO_MAIN_PATE), 500);
    }

    /**
     * process to process communication
     */
    class LoadingActivityHandler extends Handler {
        WeakReference<LoadingActivity> mActivityReference;

        LoadingActivityHandler(LoadingActivity activity) {
            mActivityReference = new WeakReference<LoadingActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final LoadingActivity activity = mActivityReference.get();
            if (activity == null) {
                return;
            }
            switch (msg.what) {
                case HANDLER_MSG_GO_MAIN_PATE:
                    /*if (mManager.isFirstRun()){
                        Intent intent = new Intent(activity, SystemSet.class);
                        activity.startActivity(intent);
                        activity.finish();
                        return;
                    }
                    mManager.setIpPort();*/
                    Intent intent = new Intent(activity, LoginActivity.class);
                    activity.startActivity(intent);
                    activity.finish();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * Thread used to init the data
     *
     * @author nicky.han
     */
    class InitApplicationTask extends AsyncTask<String, Integer, String> {
        @Override
        protected String doInBackground(String... params) {
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
//            mHandler.sendMessage(mHandler.obtainMessage(HANDLER_MSG_GO_MAIN_PATE));
            mManager.closeDBManager();
            mHandler.sendMessageDelayed(mHandler.obtainMessage(HANDLER_MSG_GO_MAIN_PATE), 1000);
        }
    }
}
